<?php
namespace app\controllers;

use app\common\corelib\CacheHelper;
use app\common\HttpCurl;
use app\logic\OrderLogic;
use app\logic\UserLogic;
use Yii;


class UserController extends BaseController
{

    /**
     * 个人中心首页
     * @apiDescription   by Jim
     * @api              {post} /user/index 个人中心首页
     * @apiName          index
     * @apiVersion       1.0.0
     * @apiParam {string} token 用户token
     * @apiGroup         User
     * @apiSampleRequest /user/index?flagsign=1
     * @apiSuccessExample {json} 获取成功
     * {
         "mobile": "12323232", // 用户手机号
        "order": {
        "toBePaid": 123, // 待支付
        "pendingDelivery": 33, // 待发货
        "shippinged": 0, // 已发货
        }
     }
     * @apiError         40004    获取失败
     */
    public function actionIndex(){
        $user = CacheHelper::get('user'.$this->user_id);
        $mobile = $user['mobile'];
        $orderLogic = new OrderLogic();
        $toBePaid = $orderLogic->getToBePaid($this->user_id);
        $pendingDelivery = $orderLogic->getPendingDelivery($this->user_id);
        $shippinged = $orderLogic->getShippinged($this->user_id);
        $this->response(['mobile'=>$mobile,'order'=>['toBePaid'=>$toBePaid,'pendingDelivery'=>$pendingDelivery,'shippinged'=>$shippinged]]);
    }

    /**
     * 获取收藏列表
     * @apiDescription   by Jim
     * @api              {post} /user/favorite-list 获取收藏列表
     * @apiName          favorite-list
     * @apiVersion       1.0.0
     * @apiParam {string} token 用户token
     * @apiGroup         User
     * @apiSampleRequest /user/favorite-list?flagsign=1
     * @apiSuccessExample {json} 获取成功
     * [{
    "goods_name": "李大唐", //商品名
    "goods_id": "ddd", // 商品ID
    "goods_pic": "", // 商品图片
    "simpleDesc": "商品名下描述",  // 商品名下描述
    "goods_price": 89.00 // float 商品价格
    }]
     * @apiError         40005    获取失败
     */
    public function actionFavoriteList(){
        $userLogic = new UserLogic();
        $favorite = $userLogic->getFavorite($this->user_id);
        foreach($favorite AS &$item){
            $item['goods_pic'] = Yii::$app->params['pic_domain'].$item['goods_pic'];
        }
        $this->response($favorite);
    }

    /**
     * 添加收藏
     * @apiDescription   by Jim
     * @api              {post} /user/add-favorite 添加收藏
     * @apiName          add-favorite
     * @apiVersion       1.0.0
     * @apiParam {string} token 用户token
     * @apiParam {int} goods_id 商品id
     * @apiGroup         User
     * @apiSampleRequest /user/add-favorite?flagsign=1
     * @apiSuccessExample {json} 获取成功
     * {

    }
     * @apiError         40006    获取失败
     */
    public function actionAddFavorite(){
        $goods_id = $this->getQueryparams('goods_id',0);
        $userLogic = new UserLogic();
        $result = $userLogic->addFavorite($this->user_id,$goods_id);
        $this->response();
    }

    /**
     * 删除收藏
     * @apiDescription   by Jim
     * @api              {post} /user/del-favorite 删除收藏
     * @apiName          del-favorite
     * @apiVersion       1.0.0
     * @apiParam {string} token 用户token
     * @apiParam {int} fav_id 收藏id
     * @apiGroup         User
     * @apiSampleRequest /user/del-favorite?flagsign=1
     * @apiSuccessExample {json} 获取成功
     * {

    }
     * @apiError         40007    获取失败
     */
    public function actionDelFavorite(){
        $fav_id = $this->getQueryparams('fav_id',0);
        $goods_id = $this->getQueryparams('goods_id',0);
        $userLogic = new UserLogic();
        $result = $userLogic->delFavorite($this->user_id,$fav_id,$goods_id);
        $this->response();
    }

    /**
     * 获取地址列表
     * @apiDescription   by Jim
     * @api              {post} /user/address-list 获取地址列表
     * @apiName          address-list
     * @apiVersion       1.0.0
     * @apiParam {string} token 用户token
     * @apiGroup         User
     * @apiSampleRequest /user/address-list?flagsign=1
     * @apiSuccessExample {json} 获取成功
     * [{
        "name": "李大唐", //收货人姓名
        "phone": "123432423423",  // 电话
        "province": "省",
        "city": "市",
        "district": "区",
        "address": "地址", // 收货地址
        "address_id": "", // 地址ID
        "is_default": 1 // 状态
    }]
     * @apiError         40008    获取失败
     */
    public function actionAddressList(){
        $userLogic = new UserLogic();
        $address = $userLogic->getAddresss($this->user_id);
        $this->response($address);
    }

    /**
     * 获取单个地址
     * @apiDescription   by Jim
     * @api              {post} /user/get-address 获取单个地址
     * @apiName          get-address
     * @apiVersion       1.0.0
     * @apiParam {string} token 用户token
     * @apiParam {int} addr_id 地址id
     * @apiGroup         User
     * @apiSampleRequest /user/get-address?flagsign=1
     * @apiSuccessExample {json} 获取成功
     * {
    "name": "李大唐", //收货人姓名
    "phone": "123432423423",  // 电话
    "province_code": "省码",
    "province": "省",
    "city_code": "市码",
    "city": "市",
    "district_code": "区码",
    "district": "区",
    "address": "地址", // 收货地址
    "address_id": "", // 地址ID
    "is_default": 1 // 状态
    }
     * @apiError         40012    获取失败
     */
    public function actionGetAddress(){
        $addr_id = $this->getQueryparams('addr_id',0);
        $userLogic = new UserLogic();
        $address = $userLogic->getAddress($this->user_id,$addr_id);
        $address['is_default'] = (int)$address['is_default'];
        $this->response($address);
    }

    /**
     * 添加地址
     * @apiDescription   by Jim
     * @api              {post} /user/add-address 编辑地址
     * @apiName          add-address
     * @apiVersion       1.0.0
     * @apiParam {string} token 用户token
     * @apiParam {string} name 收货人
     * @apiParam {string} phone 电话
     * @apiParam {string} province_code 省码
     * @apiParam {string} city_code 市码
     * @apiParam {string} district_code 区码
     * @apiParam {string} address 详细地址
     * @apiParam {int} is_default 是否默认
     * @apiGroup         User
     * @apiSampleRequest /user/edit-address?flagsign=1
     * @apiSuccessExample {json} 获取成功
     * {

    }
     * @apiError         40009    获取失败
     */
    public function actionAddAddress(){
        $name = $this->getQueryparams('name','');
        $phone = $this->getQueryparams('phone','');
        $province_code = $this->getQueryparams('province_code','');
        $city_code = $this->getQueryparams('city_code','');
        $district_code = $this->getQueryparams('district_code','');
        $address = $this->getQueryparams('address','');
        $is_default = $this->getQueryparams('is_default',0);
        $userLogic = new UserLogic();
        $address = $userLogic->addAddress($this->user_id,$name,$phone,$province_code,$city_code,$district_code,$address,$is_default);
        $this->response($address);
    }

    /**
     * 编辑地址
     * @apiDescription   by Jim
     * @api              {post} /user/edit-address 编辑地址
     * @apiName          edit-address
     * @apiVersion       1.0.0
     * @apiParam {string} token 用户token
     * @apiParam {int} addr_id 地址id
     * @apiParam {string} name 收货人
     * @apiParam {string} phone 电话
     * @apiParam {string} province_code 省码
     * @apiParam {string} city_code 市码
     * @apiParam {string} district_code 区码
     * @apiParam {string} address 详细地址
     * @apiParam {int} is_default 是否默认
     * @apiGroup         User
     * @apiSampleRequest /user/edit-address?flagsign=1
     * @apiSuccessExample {json} 获取成功
     * {

    }
     * @apiError         40010    获取失败
     */
    public function actionEditAddress(){
        $addr_id = $this->getQueryparams('addr_id',0);
        $name = $this->getQueryparams('name','');
        $phone = $this->getQueryparams('phone','');
        $province_code = $this->getQueryparams('province_code','');
        $city_code = $this->getQueryparams('city_code','');
        $district_code = $this->getQueryparams('district_code','');
        $address = $this->getQueryparams('address','');
        $is_default = $this->getQueryparams('is_default',0);
        $userLogic = new UserLogic();
        $address = $userLogic->editAddress($this->user_id,$addr_id,$name,$phone,$province_code,$city_code,$district_code,$address,$is_default);
        $this->response($address);
    }

    /**
     * 删除地址
     * @apiDescription   by Jim
     * @api              {post} /user/del-address 删除地址
     * @apiName          del-address
     * @apiVersion       1.0.0
     * @apiParam {string} token 用户token
     * @apiParam {int} addr_id 地址id
     * @apiGroup         User
     * @apiSampleRequest /user/del-address?flagsign=1
     * @apiSuccessExample {json} 获取成功
     * {
    }
     * @apiError         40011    获取失败
     */
    public function actionDelAddress(){
        $addr_id = $this->getQueryparams('addr_id',0);
        $userLogic = new UserLogic();
        $result = $userLogic->delAddress($this->user_id,$addr_id);
        $this->response();
        /*if($result){
            $this->response();
        }else{
            $this->error('40011','默认地址不能删除');
        }*/
    }

    /**
     * 发送短信
     * @apiDescription   by Jim
     * @api              {post} /user/get-caphta 发送短信
     * @apiName          get-caphta
     * @apiVersion       1.0.0
     * @apiParam {string} mobile 电话
     * @apiGroup         User
     * @apiSampleRequest /user/get-caphta?flagsign=1
     * @apiSuccessExample {json} 获取成功
     * {
    }
     * @apiError         40000    获取失败
     */
    public function actionGetCaphta(){
        $mobile = $this->getQueryparams('mobile','');
        $result = HttpCurl::zj_post('/gw/userAuth/get_smscode',['mobileNum'=>$mobile]);
        if($result['errcode']==0){
            $this->response();
        }else{
            $this->error('40000',$result['errmsg']);
        }
    }

    /**
     * 注册
     * @apiDescription   by Jim
     * @api              {post} /user/register 注册
     * @apiName          register
     * @apiVersion       1.0.0
     * @apiParam {string} mobile 电话
     * @apiParam {string} caphtaCode 验证码
     * @apiParam {string} password 密码
     * @apiGroup         User
     * @apiSampleRequest /user/register?flagsign=1
     * @apiSuccessExample {json} 获取成功
     * {
    }
     * @apiError         40001    获取失败
     */
    public function actionRegister(){
        $mobile = $this->getQueryparams('mobile','');
        $caphtaCode = $this->getQueryparams('caphtaCode','');
        $password = $this->getQueryparams('password','');
        $result = HttpCurl::zj_post('/gw/userAuth/register',['login'=>['mobileNum'=>$mobile,'smsCode'=>$caphtaCode,'password'=>$password]]);
        if($result['errcode']==0){
            $userLogic = new UserLogic();
            $user = $userLogic->addUser($mobile,$result['token'],$password);
            $expireIn = $result['expireIn']!=-1?$result['expireIn']:0;
            CacheHelper::set('user_token_'.$result['token'],$user,$expireIn);
            CacheHelper::set('user'.$user['user_id'],$user,$expireIn);
            $this->response(['token'=>$result['token']]);
        }else{
            $this->error('40001',$result['errmsg']);
        }

    }

    /**
     * 登录
     * @apiDescription   by Jim
     * @api              {post} /user/login 登录
     * @apiName          login
     * @apiVersion       1.0.0
     * @apiParam {string} mobile 电话
     * @apiParam {string} password 密码
     * @apiGroup         User
     * @apiSampleRequest /user/login?flagsign=1
     * @apiSuccessExample {json} 获取成功
     * {
    }
     * @apiError         40002    获取失败
     */
    public function actionLogin(){
        $mobile = $this->getQueryparams('mobile','');
        $password = $this->getQueryparams('password','');
        $result = HttpCurl::zj_post('/gw/userAuth/logina',['login'=>['mobileNum'=>$mobile,'password'=>$password]]);
        if($result['errcode']==0){
            $userLogic = new UserLogic();
            $user = $userLogic->updateUser($mobile,$result['token']);
            $expireIn = $result['expireIn']!=-1?$result['expireIn']:0;
            CacheHelper::set('user_token_'.$result['token'],$user,$expireIn);
            CacheHelper::set('user'.$user['user_id'],$user,$expireIn);
            $this->response(['token'=>$result['token']]);
        }else{
            $this->error('40002',$result['errmsg']);
        }

    }

    /**
     * 修改密码
     * @apiDescription   by Jim
     * @api              {post} /user/update-password 修改密码
     * @apiName          update-password
     * @apiVersion       1.0.0
     * @apiParam {string} mobile 电话
     * @apiParam {string} caphtaCode 验证码
     * @apiParam {string} password 密码
     * @apiGroup         User
     * @apiSampleRequest /user/update-password?flagsign=1
     * @apiSuccessExample {json} 获取成功
     * {
    }
     * @apiError         40003    获取失败
     */
    public function actionUpdatePassword(){
        $mobile = $this->getQueryparams('mobile','');
        $caphtaCode = $this->getQueryparams('caphtaCode','');
        $password = $this->getQueryparams('password','');
        $userLogic = new UserLogic();
        $time = time();
        $nonce = $this->GetRandStr(8);
        $appKey = \Yii::$app->params["zjapi"]["appKey"];
        $signature = array($appKey,$mobile,$caphtaCode,$password,$nonce,$time);
        sort($signature,2);
        $signature = implode('',$signature);
        $signature = md5($signature);
        $result = HttpCurl::zj_post('/gw/userAuth/resetPasswordWithSmscode',['login'=>['mobileNum'=>$mobile,'newpassword'=>$password,'smsCode'=>$caphtaCode,'timeStamp'=>$time,'nonce'=>$nonce,'signature'=>$signature]]);
        if($result['errcode']==0){
            $this->response();
        }else{
            $this->error('40003',$result['errmsg']);
        }

    }

    public function GetRandStr($length)
    {
        $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $len = strlen($str) - 1;
        $randstr = '';
        for ($i = 0; $i < $length; $i++) {
            $num = mt_rand(0, $len);
            $randstr .= $str[$num];
        }
        return $randstr;
    }

}